#include "my_task.h"
#include "task_data.h"
#include "cJSON.h"
#include <stdio.h>
#include <string.h>

#include "iosensor.h"
#include "esp8266.h"
#include "step_motor.h"
#include "sht30_i2c_drv.h"
#include "bmp280.h"

#include "driver_pwm.h"
#include "driver_task.h"
#include "driver_adc.h"
#include "driver_usart.h"
#include "driver_delay.h"
#include "driver_key.h"
#include "driver_tool.h"
#include "i2c.h"

#include "display.h"
#include "pid.h"
#include "bmp280.h"

enum DEVICE_TYPE{
	DEVICE_MOTOE = 1,
	DEVICE_LIGHT,
	DEVICE_SOIL, // 湿度设置
};

static SENSOR_CTL g_sensor_ctl = {0};
static SENSOR_CTL g_sensor_tar = {0};
static SENSOR_CTL g_sensor_ctl_his = {0};
static SYS_CTL g_sys_ctl = {0};


static void get_temp_data(void)
{
	if (SHT30_Read_Dat(g_sensor_ctl.sht32_recv) != HAL_OK) {
		GUA_LOGE("read sht30 data err!");
	} else {
		if (SHT30_Dat_To_Float(g_sensor_ctl.sht32_recv, &g_sensor_ctl.val_Temp, &g_sensor_ctl.val_Hum) == 0) {
			g_sensor_ctl.val_Temp = g_sensor_ctl.val_Temp/100;
			g_sensor_ctl.val_Hum = g_sensor_ctl.val_Hum/100;
			// GUA_LOGI("temperature = %d, humidity = %d", g_sensor_ctl.val_Temp, g_sensor_ctl.val_Hum);
		} else {
			GUA_LOGE("chenage sht30 data err!");
		}
	}


	#ifdef DEV_LIGHT
	g_sensor_ctl.val_Light  = (int)get_light();
	#endif

	#ifdef DEV_PEOPLE
	g_sensor_ctl.val_people = get_people();
	#endif

	#ifdef DEV_SMOCK
	g_sensor_ctl.val_smoke  = get_smoke();
	#endif

	#ifdef DEV_BMP280
	if (user_get_bmp280(&temperature, &pressure, &Alt, &humidit) == false) {
		GUA_LOGE("read bmp280 data err!");
	}
	g_sensor_ctl.val_pressure = (uint32_t) pressure;
	g_sensor_ctl.val_altitude =  (uint32_t) Alt*1000;
	#endif

	#ifdef DEV_SOILHUM
	g_sensor_ctl.val_soil = get_soil_humidity();
	#endif

	#ifdef DEV_WIND_SPEED
	g_sensor_ctl.val_wind_speed = (uint32_t) get_wind_speed();
	#endif

	#ifdef DEV_WIND_DIRE
	g_sensor_ctl.val_wind_direction = (uint32_t) get_wind_direction();
	#endif

	GUA_LOGI("val_soil %d", g_sensor_ctl.val_soil);
}

static void timer_task(void)
{
	if (g_sensor_ctl.led_status == 0 || g_sensor_ctl.led_status == 1) {
		g_sensor_ctl.led_status = !g_sensor_ctl.led_status;
	}
	if (g_sensor_ctl.led_status) {
		HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_RESET);
	} else {
		HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_SET);
	}
}


static void sand_message(void)
{
	char jsondata[128] = {0};
#ifdef WIFI_ENABLE
	sprintf(jsondata,
		"{\"user\":\"home\",\"hum\":%d,\"temp\":%d,\"lit\":%d,\"soil\":%d}\r\n",
		g_sensor_ctl.val_Hum ,
		g_sensor_ctl.val_Temp,
		g_sensor_ctl.val_Light,
		g_sensor_ctl.val_soil
	);

	// WiFi初始化以后给服务器发数据
	if (g_sys_ctl.wifi_status == 1) {
		esp_send_data(jsondata);
	}
#endif

#ifdef BLE_ENABLE
	sprintf((char *)g_sys_ctl.send_buf, "{\"T\":%d}\r\n", g_sensor_ctl.val_Temp);
	HAL_UART_Transmit_DMA(&huart2, g_sys_ctl.send_buf, strlen((char *)g_sys_ctl.send_buf));
	delay_ms(10);

	sprintf((char *)g_sys_ctl.send_buf, "{\"H\":%d}\r\n",g_sensor_ctl.val_Hum);
	HAL_UART_Transmit_DMA(&huart2, g_sys_ctl.send_buf, strlen((char *)g_sys_ctl.send_buf));
	delay_ms(10);

	sprintf((char *)g_sys_ctl.send_buf, "{\"P\":%d}\r\n", g_sensor_ctl.val_pmw);
	HAL_UART_Transmit_DMA(&huart2, g_sys_ctl.send_buf, strlen((char *)g_sys_ctl.send_buf));
	delay_ms(10);

	sprintf((char *)g_sys_ctl.send_buf, "{\"K\":%d}\r\n", g_sys_ctl.pid_hot_ctl);
	HAL_UART_Transmit_DMA(&huart2, g_sys_ctl.send_buf, strlen((char *)g_sys_ctl.send_buf));
	delay_ms(10);
#endif
}


// PID
void task_pid(void)
{
	uint16_t how_pwm;
	if (g_sys_ctl.pid_hot_ctl == 1) {
		if (g_sensor_tar.val_Temp > g_sensor_ctl.val_Temp) {
			how_pwm = user_pid_conctrl(g_sensor_tar.val_Temp, g_sensor_ctl.val_Temp);
			set_pwm_channel_2_1(how_pwm);
			g_sensor_ctl.val_pmw = how_pwm;
			set_fun(0);
		} else if (g_sensor_ctl.val_Temp > g_sensor_tar.val_Temp){
			set_fun(1);
			set_pwm_channel_2_1(0);
			g_sensor_ctl.val_pmw = 0;
		}
	} else {
		user_enable_pid(0,0);
		set_fun(0);
		set_pwm_channel_2_1(0);
		g_sensor_ctl.val_pmw = 0;
	}

}


static void task_1hz(void)
{
	get_temp_data();
	updata_time_task_time();
	sand_message();
	task_pid();
}


static void delay_colse_triger(void)
{
	GUA_LOGI("close triger!");
	set_control(0);
	beep_ding();
}

static void delay_open_triger(void)
{
	GUA_LOGI("open triger!");
	set_control(1);
	beep_ding();
}


static void message_handle(char *strbuf)
{
#ifdef WIFI_ENABLE
	uint32_t data_type = 0;
	uint32_t data_key = 0;
	uint32_t data_value = 0;
	cJSON *parsed_json = cJSON_Parse(strbuf);
	if (parsed_json == NULL) {
		// 解析失败处理
		GUA_LOGE("Parse error\n");
	} else {
		cJSON *type = cJSON_GetObjectItem(parsed_json, "type");
		if (type != NULL) {
			GUA_LOGI("message get value type [%d]", type->valueint);
			data_type = type->valueint;
		}
		cJSON *key = cJSON_GetObjectItem(parsed_json, "key");
		if (key != NULL) {
			GUA_LOGI("message get value key: [%d]", key->valueint);
			data_key = key->valueint;
		}
		cJSON *val = cJSON_GetObjectItem(parsed_json, "val");
		if (val != NULL) {
			GUA_LOGI("message get value val: [%d]", val->valueint);
			data_value = val->valueint;
		}
		// 继续解析其他数据...
		cJSON_Delete(parsed_json);
	}

	switch (data_type){
		case DEVICE_MOTOE :{
			if (data_key) {
				register_run_single_time_task(delay_open_triger, data_value); // 单次定时执行任务注册函数
			} else {
				register_run_single_time_task(delay_colse_triger, data_value); // 单次定时执行任务注册函数
			}
			break;
		}
		case DEVICE_LIGHT :{
			if (data_key) {
				g_sys_ctl.light_run_flag = 1;
				g_sensor_tar.val_Light = data_value;
			} else {
				g_sys_ctl.light_run_flag = 0;
				g_sensor_tar.val_Light = 0;
			}
			break;
		}
		case DEVICE_SOIL :{
			if (data_key) {
				g_sys_ctl.soil_run_flag = 1;
				g_sensor_tar.val_soil = data_value;
			} else {
				g_sys_ctl.soil_run_flag = 0;
				g_sensor_tar.val_soil = 0;
			}
			break;
		}
		default:
			break;
	}
#endif
#ifdef BLE_ENABLE
	if (strstr(strbuf,"DT") != NULL) {
		g_sensor_tar.val_Temp = ((strbuf[3]-0x30)*10) + (strbuf[4]-0x30);
		beep_ding(); // 接收到数据丁一声
	}
#endif
}


void task_main()
{
	int32_t rev = 0;
#ifdef DEV_LIGHT
	int32_t light_control = 0;
	int32_t soil_control = 1;
#endif
	GUA_LOGI("task_main begin.\r\n");

	strat_usart_interupt();
	init_PWM();
	init_timer_task();

	// 初始化SHT30
	SHT30_Reset();
	rev = SHT30_Init();
	if (rev != HAL_OK) {
		GUA_LOGI("sht30 init fail.\r\n");
	}

#ifdef DEV_BMP280
	// 气压初始化
	rev = user_init_bmp280();
	if (rev == false) {
		GUA_LOGE("bmp280 init error!\r\n");
	}

	while(1) {
		delay_ms(1000);
	}
#endif
	// 初始化LED
	OLED_Init();
	OLED_ColorTurn(0);//0正常显示，1 反色显示
	OLED_DisplayTurn(0);//0正常显示 1 屏幕翻转显示

	get_temp_data(); // 显示之前先获取一遍数值
	g_sensor_tar.val_Temp  = g_sensor_ctl.val_Temp + 2;
	g_sensor_tar.val_Hum   = g_sensor_ctl.val_Hum+ 10;
	g_sensor_tar.val_Light = g_sensor_ctl.val_Light + 100;
#ifdef DEV_CO2
	g_sensor_tar.val_Co2 = 58500;
#endif
	g_sys_ctl.work_status  = 0;
	g_sensor_tar.val_soil  = g_sensor_ctl.val_soil + 10;

	beep_ding();
#ifdef WIFI_ENABLE
	char screen_buf[] = "connect WiFi..";
	OLED_ShowString(0, 0, (uint8 *)screen_buf, 16, 1);
	OLED_Refresh();
	// 初始化WiFi
	g_sys_ctl.wifi_status = 0;
	if (inti_esp8266() == 0 ) {
		g_sys_ctl.wifi_status = 1;
	}
	OLED_Clear();
#endif
#ifdef BLE_ENABLE
	g_sys_ctl.wifi_status = 1;
#endif

	// 初始化按钮
	key_config_init(&g_sensor_ctl.key_value1);
	key_config_init(&g_sensor_ctl.key_value2);
	key_config_init(&g_sensor_ctl.key_value3);
	key_config_init(&g_sensor_ctl.key_value4);

	beep_ding();

	register_interupt(task_1hz, INTER_1000MS); // 500毫秒周期函数检测 温湿度数据
	register_interupt(timer_task, INTER_100MS);
	// register_interupt(sand_message,INTER_1000MS);
	// register_interupt(updata_time_task_time,INTER_1000MS);
	// register_interupt(task_pid,INTER_1000MS);


	g_sys_ctl.main_init_ok = 1;
	while(1) {

		display_oled(&g_sensor_ctl_his, &g_sensor_ctl, &g_sensor_tar, &g_sys_ctl); // 刷新界面

		if (g_sys_ctl.message_recv_falg) {
			g_sys_ctl.message_recv_falg = 0;
			message_handle((char *) g_sys_ctl.message_Buf);
			memset(g_sys_ctl.message_Buf, 0, sizeof(g_sys_ctl.message_Buf));
		}

		// 温度判断
		if (g_sensor_ctl.val_Temp > g_sensor_tar.val_Temp) { // 温度传感器超标以后打开风扇， 同时报警
			GUA_LOGW("temp now[%d] > tar[%d]", g_sensor_ctl.val_Temp, g_sensor_tar.val_Temp);
			// beep_ding();
			// set_fun(1);
		} else {
			// set_fun(0);
		}

		// 湿度判断
		if (g_sensor_ctl.val_Hum > g_sensor_tar.val_Hum) { // 湿度传感器超过阈值以后报警
			GUA_LOGW("hum now[%d] > tar[%d]", g_sensor_ctl.val_Hum, g_sensor_tar.val_Hum);
			// beep_ding();
		}

	#ifdef DEV_PEOPLE
		// 有人判断
		if (g_sensor_ctl.val_people == 1) {
			GUA_LOGW("is people");
			beep_ding();
		}
	#endif

	#ifdef DEV_CO2
		// 二氧化碳判断
		if (g_sensor_ctl.val_Co2 > g_sensor_tar.val_Co2) {
			GUA_LOGW("co2 now[%d] > target[%d]", g_sensor_ctl.val_Co2, g_sensor_tar.val_Co2);
			beep_ding();
		}
	#endif

	#ifdef DEV_LIGHT
		// 光照判断
		if (g_sensor_ctl.val_Light > g_sensor_tar.val_Light + 50 && g_sys_ctl.light_run_flag == 1 && light_control != 1) { // 光照传感器超过阈值以后报警
			GUA_LOGW("light now[%d] > tar[%d]", g_sensor_ctl.val_Light, g_sensor_tar.val_Light);
			// beep_ding();
			// STEP_MOTOR_LOOP(1,1,2);  //步进电机正传
			// light_control = 1;
		} else if (g_sensor_ctl.val_Light < g_sensor_tar.val_Light - 50 && g_sys_ctl.light_run_flag == 1  && light_control != 2) { // 光照传感器超过阈值以后报警
			GUA_LOGW("light now[%d] < tar[%d]", g_sensor_ctl.val_Light, g_sensor_tar.val_Light);
			// beep_ding();
			// STEP_MOTOR_LOOP(0,1,2);  //步进电机反传
			// light_control = 2;
		}
	#endif

	#ifdef DEV_SMOCK
		// 烟雾报警
		if (g_sensor_ctl.val_smoke) {
			GUA_LOGW("smoke[%d]", g_sensor_ctl.val_smoke);
			beep_ding();
		}
	#endif

		// 土壤湿度判断
	#ifdef DEV_SOILHUM
		// if (g_sensor_ctl.val_soil > g_sensor_tar.val_soil) {
		// 	GUA_LOGW("soil[%d]>tar[%d]", g_sensor_ctl.val_soil, g_sensor_tar.val_soil);
		// 	beep_ding();
		// 	// 如果湿度小于目标值就打开水泵
		// 	set_control(1);
		// } else {
		// 	set_control(0);
		// }

		// 土壤湿度判断
		if (g_sys_ctl.soil_run_flag == 1) {
			if (g_sensor_ctl.val_soil > g_sensor_tar.val_soil+10) { //
				GUA_LOGW("soil now[%d] > tar[%d]", g_sensor_ctl.val_soil, g_sensor_tar.val_soil);
				beep_ding();
				set_control(1);
			} else {
				set_control(0);
			}
		}

	#endif

		run_single_time_task(); // 执行定时任务；
		run_task(); // 执行周期定时函数
		delay_ms(50);
	}
}


void base_task(void)
{
#ifdef BOWUGUAN
	register_interupt(get_temp_data, INTER_500MS ); // 500毫秒周期函数检测 温湿度数据
	register_interupt(sand_message,INTER_300MS);
	while (1) {
		interrupt_task();
		delay_ms(10);
		run_task();
	}

#endif
	uint8 key = 0;
	uint8 histery_key1;
	uint8 histery_key2;
	uint8 histery_key3;
	uint8 histery_key4;
	uint8 key_sta1, key_sta2, key_sta3, key_sta4, key_sta5, key_sta6, key_sta7, key_sta8;

	while (g_sys_ctl.main_init_ok) {
		delay_ms(2);
	}
	GUA_LOGI("base_task begin.\r\n");

	while(1) {
		delay_ms(10);
		interrupt_task(); // 10毫秒周期判断


		if(Rx_Flag){  // Receive flag
			Rx_Flag=0;	// clean flag
			HAL_UART_Transmit(&huart1, Rx_Buf, Rx_Len, 0xFFFF);
		}

		if (g_sys_ctl.wifi_status == 1) {
			if(Rx2_Flag){  // Receive flag
				Rx2_Flag=0;	// clean flag
				// HAL_UART_Transmit(&huart1, Rx2_Buf, Rx2_Len, 0xFFFF);
				// GUA_LOGI("esp recv:%s", Rx2_Buf);
				memcpy(g_sys_ctl.message_Buf, Rx2_Buf, Rx2_Len);
				g_sys_ctl.message_recv_falg = 1;
			}
		}

		#ifdef DEV_CO2
		if (Rx3_Flag) {  // Receive flag
			Rx3_Flag=0;	// clean flag
			// HAL_UART_Transmit(&huart1, Rx3_Buf, Rx3_Len, 0xFFFF);
			if(Rx3_Len >= 6) {
				// GUA_LOGI("Rx3_Len:[%d] %x %x %x %x %x %x", Rx3_Len, Rx3_Buf[0], Rx3_Buf[1], Rx3_Buf[2], Rx3_Buf[3], Rx3_Buf[4], Rx3_Buf[5]);

				g_sensor_ctl.val_Co2 =  Rx3_Buf[1]*256+Rx3_Buf[2];// B2*256+B3

				// GUA_LOGI("data_CO2:%d", g_sensor_ctl.val_Co2);
			}
		}
		#endif

		key = HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin);
		if (key == 1) {
			if (histery_key1 != key) {
				g_sensor_ctl.key_value1.flag.key_state = KEY_STATE_PRESS;	//按下
				g_sensor_ctl.key_value1.flag.check = 1;
				g_sensor_ctl.key_value1.time_continus = 0;		//按键持续时间置零，准备开始计时
				histery_key1 = key;
			}
		} else {
			if (histery_key1 != key) {
				g_sensor_ctl.key_value1.flag.key_state = KEY_STATE_RELEASE;	//松开
				g_sensor_ctl.key_value1.flag.check = 1;
				g_sensor_ctl.key_value1.time_idle = 0;			//按键空闲时间置零，准备开始计时
				histery_key1 = key;
			}
		}
		key_Process(&g_sensor_ctl.key_value1);
		key_sta1 = key_scan(&g_sensor_ctl.key_value1);

		key = HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin);
		if (key == 1) {
			if (histery_key2 != key) {
				g_sensor_ctl.key_value2.flag.key_state = KEY_STATE_PRESS;	//按下
				g_sensor_ctl.key_value2.flag.check = 1;
				g_sensor_ctl.key_value2.time_continus = 0;		//按键持续时间置零，准备开始计时
				histery_key2 = key;
			}
		} else {
			if (histery_key2 != key) {
				g_sensor_ctl.key_value2.flag.key_state = KEY_STATE_RELEASE;	//松开
				g_sensor_ctl.key_value2.flag.check = 1;
				g_sensor_ctl.key_value2.time_idle = 0;			//按键空闲时间置零，准备开始计时
				histery_key2 = key;
			}
		}
		key_Process(&g_sensor_ctl.key_value2);
		key_sta2 = key_scan(&g_sensor_ctl.key_value2);

		key = HAL_GPIO_ReadPin(KEY3_GPIO_Port, KEY3_Pin);
		if (key == 1) {
			if (histery_key3 != key) {
				g_sensor_ctl.key_value3.flag.key_state = KEY_STATE_PRESS;	//按下
				g_sensor_ctl.key_value3.flag.check = 1;
				g_sensor_ctl.key_value3.time_continus = 0;		//按键持续时间置零，准备开始计时
				histery_key3 = key;
			}
		} else {
			if (histery_key3 != key) {
				g_sensor_ctl.key_value3.flag.key_state = KEY_STATE_RELEASE;	//松开
				g_sensor_ctl.key_value3.flag.check = 1;
				g_sensor_ctl.key_value3.time_idle = 0;			//按键空闲时间置零，准备开始计时
				histery_key3 = key;
			}
		}
		key_Process(&g_sensor_ctl.key_value3);
		key_sta3 = key_scan(&g_sensor_ctl.key_value3);

		key = HAL_GPIO_ReadPin(KEY4_GPIO_Port, KEY4_Pin);
		if (key == 1) {
			if (histery_key4 != key) {
				g_sensor_ctl.key_value4.flag.key_state = KEY_STATE_PRESS;	//按下
				g_sensor_ctl.key_value4.flag.check = 1;
				g_sensor_ctl.key_value4.time_continus = 0;		//按键持续时间置零，准备开始计时
				histery_key4 = key;
			}
		} else {
			if (histery_key4 != key) {
				g_sensor_ctl.key_value4.flag.key_state = KEY_STATE_RELEASE;	//松开
				g_sensor_ctl.key_value4.flag.check = 1;
				g_sensor_ctl.key_value4.time_idle = 0;			//按键空闲时间置零，准备开始计时
				histery_key4 = key;
			}
		}
		key_Process(&g_sensor_ctl.key_value4);
		key_sta4 = key_scan(&g_sensor_ctl.key_value4);

		key_sta5 = HAL_GPIO_ReadPin(KEY5_GPIO_Port, KEY5_Pin);
		key_sta6 = HAL_GPIO_ReadPin(KEY6_GPIO_Port, KEY6_Pin);
		key_sta7 = HAL_GPIO_ReadPin(KEY7_GPIO_Port, KEY7_Pin);
		key_sta8 = HAL_GPIO_ReadPin(KEY8_GPIO_Port, KEY8_Pin);

		// 键值处理
		if (key_sta1 == EVENT_SHORT_CLICK) {
			g_sensor_tar.val_Temp++;
			g_sensor_tar.val_soil++;
			g_sys_ctl.key_up_flag = 1;
			GUA_LOGI("key_sta1");
		}else if (key_sta1 == EVENT_LONG_CLICK) {
			GUA_LOGI("key_sta1 long");
			g_sys_ctl.work_status = !g_sys_ctl.work_status;
			g_sys_ctl.key_up_flag = 1;
			user_enable_pid(1, g_sensor_tar.val_Temp); // 输入使能和状态
			beep_ding();
			g_sys_ctl.pid_hot_ctl = 1;
		}


		if (key_sta2 == EVENT_SHORT_CLICK) {
			g_sensor_tar.val_Temp--;
			g_sensor_tar.val_soil--;
			GUA_LOGI("key_sta2");
			g_sys_ctl.key_up_flag = 1;
		}else if (key_sta2 == EVENT_LONG_CLICK) {
			GUA_LOGI("key 2 log");
			g_sys_ctl.play_status = 1;
			g_sys_ctl.key_up_flag = 1;
			user_enable_pid(0, 0); // 输入使能和状态
			beep_ding();
			g_sys_ctl.pid_hot_ctl = 0;
		}

		if (key_sta3 == EVENT_SHORT_CLICK) {
			g_sensor_tar.val_Hum++;
			GUA_LOGI("key_sta3");
			g_sys_ctl.key_up_flag = 1;
		}

		if (key_sta4 == EVENT_SHORT_CLICK) {
			g_sensor_tar.val_Hum--;
			GUA_LOGI("key_sta4");
			g_sys_ctl.key_up_flag = 1;
		}

		if (key_sta5 == 1) {
			g_sys_ctl.key_up_flag = 1;
			g_sensor_tar.val_Light ++;
			GUA_LOGI("key_sta5 tar_Light:%d", g_sensor_tar.val_Light);
		}

		if (key_sta6 == 1) {
			g_sys_ctl.key_up_flag = 1;
			g_sensor_tar.val_Light --;
			GUA_LOGI("key_sta6 tar_Light:%d", g_sensor_tar.val_Light);
		}


		if (key_sta7 == 1) {
			g_sys_ctl.key_up_flag = 1;
		#ifdef DEV_CO2
			g_sensor_tar.val_Co2++;
		#endif
		}

		if (key_sta8 == 1) {
			g_sys_ctl.key_up_flag = 1;
		#ifdef DEV_CO2
			g_sensor_tar.val_Co2--;
		#endif
		}


	}
}














